<!--
  * 欠款收款单
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form>
      <a-row :gutter="[8, 10]">
        <a-col :span="{ sm: 7, md: 6 }">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="单据编号" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.no" placeholder="单据编号" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="门店" class="smart-margin-bottom0">
            <Select name="Store" v-model:value="queryForm.store_id" placeholder="门店" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="业务员" class="smart-margin-bottom0">
            <Select name="Salesman" v-model:value="queryForm.salesman_id" placeholder="业务员" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <SearchFormCollapse v-model="expand" />
          </a-button-group>
        </a-col>
      </a-row>
      <a-row :gutter="[8, 10]" class="smart-margin-top10" v-show="expand">
        <a-col :span="4">
          <a-form-item label="结算状态" class="smart-margin-bottom0">
            <EnumSelect enum-name="SETTLEMENT_STATUS" v-model:value="queryForm.settlement_status" placeholder="结算状态" @submit="onSearch" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block"> </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{}">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'no'">
            <CopyText :text="text">
              <a @click="toSaleOrder(record)">{{ text }}</a>
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'settlement_status'">
            {{ getDescByValue('SETTLEMENT_STATUS', text) }}
          </template>
          <template v-if="column.dataIndex === 'accountPeriod'">
            <div class="smart-table-operate">
              <a-image :width="record.accountPeriod?.payment_voucher ? 30 : 50" :src="record.accountPeriod?.payment_voucher || failImg" />
            </div>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <template v-if="record.settlement_status === SETTLEMENT_STATUS.UNSETTLED.value">
                <a-button @click="changeSettlementModal(true, record)" type="link" v-privilege="'goods:update'">收款</a-button>
              </template>
            </div>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <a-table-summary-cell :index="0">总计</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.total_discounted_amount.toFixed(2) }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.total_sign_amount.toFixed(2) }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.total_account_period_amount.toFixed(2) }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell :index="columns.length" />
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
    <!-- 收款 -->
    <a-modal :open="showSettlementModal" title="欠款收款" @cancel="changeSettlementModal(false)" @ok="submitSettlementForm">
      <a-form ref="formRef" :model="settlementFormData" :labelCol="{ span: 4 }" :rules="settlementRules">
        <a-form-item label="业务员" name="salesman_id">
          <Select name="Salesman" v-model:value="settlementFormData.salesman_id" :disabled="disabledSalesmanSelected" placeholder="请选择业务员" />
        </a-form-item>
        <a-form-item label="收款金额" name="account_period_amount" required>
          <a-input-number v-model:value="settlementFormData.account_period_amount" :precision="2" disabled placeholder="请输入" />
        </a-form-item>
        <a-form-item label="结算方式" name="payment_method">
          <a-select v-model:value="settlementFormData.payment_method">
            <a-select-option :value="1">现金</a-select-option>
            <a-select-option :value="2">公户</a-select-option>
            <a-select-option :value="3">预存款</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="欠款日期" name="account_period_date">
          <a-date-picker style="width: 100%" v-model:value="settlementFormData.account_period_date" valueFormat="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="上传凭证" name="payment_voucher">
          <FileUpload v-model:value="settlementFormData.payment_voucher" :default-file-list="settlementFormData.payment_voucher" buttonText="上传凭证" :maxUploadSize="1" :maxSize="5" accept=".jpeg,.jpg,.png" />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-input v-model:value="settlementFormData.remark" placeholder="请输入" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>
<script setup lang="ts">
import _ from 'lodash'
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import Select from '@/components/business/select/index.vue'
import SearchFormCollapse from '@/components/support/search-form-collapse/index.vue'
import { accountingPreiodApi } from '@/api/business/finance/accounting-preiod-api'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import { SETTLEMENT_STATUS } from '@/constants/business/orders-const'
import { message } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import TableOperator from '@/components/support/table-operator/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import FileUpload from '@/components/support/file-upload/index.vue'
import failImg from '@/assets/images/notice/failImg.png'
const appConfigStore = useAppConfigStore()
const { getDescByValue } = useEnums()

// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY, expand } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '单据编号',
    dataIndex: 'no',
    width: appConfigStore.$state.compactFlag ? 240 : 270
  },
  {
    title: '门店名称',
    dataIndex: ['store', 'store_name']
  },
  {
    title: '订单金额',
    dataIndex: 'order_total_price'
  },
  {
    title: '签收金额',
    dataIndex: ['sign', 'sign_amount']
  },
  {
    title: '业务员',
    dataIndex: ['salesman', 'rename']
  },
  {
    title: '司机',
    dataIndex: ['delivery', 'driver', 'name']
  },
  {
    title: '车辆',
    dataIndex: ''
  },
  {
    title: '结算状态',
    dataIndex: 'settlement_status'
  },
  {
    title: '结算金额',
    dataIndex: ['accountPeriod', 'account_period_amount']
  },
  {
    title: '结算日期',
    dataIndex: ['accountPeriod', 'create_time']
  },
  {
    title: '结算备注',
    dataIndex: ['accountPeriod', 'remark']
  },
  {
    title: '签收日期',
    dataIndex: ['sign', 'create_time']
  },
  {
    title: '备注',
    dataIndex: 'remark'
  },
  {
    title: '收款凭证',
    dataIndex: 'accountPeriod'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right'
  }
])
// ---------------------------- 查询数据表单和方法 ----------------------------
const total_amount = ref({
  total_account_period_amount: 0,
  total_detail_sum: 0,
  total_discounted_amount: 0,
  total_sign_amount: 0
})
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData } = useQuery({
  fetchDataApi: async (params) => {
    const res = await accountingPreiodApi.queryList(params)
    total_amount.value = res.data.sumData
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {
    no: '',
    settlement_status: undefined,
    store_id: undefined,
    salesman_id: undefined,
    create_time: DEFAULT_TIME_RANGE.value
  },
  queryFormOp: {
    no: QUERY_FORM_OP['模糊查询'],
    settlement_status: QUERY_FORM_OP['全等查询'],
    store_id: QUERY_FORM_OP['全等查询'],
    salesman_id: QUERY_FORM_OP['全等查询'],
    create_time: QUERY_FORM_OP['范围查询']
  }
})
onMounted(queryData)

// 跳转至销售单
const router = useRouter()
function toSaleOrder(record) {
  if (record.type == 1 && record.order_type == 1) {
    router.push(`/sale/sales?no=${record.no}`)
  } else if (record.type == 2 && record.order_type == 1) {
    router.push(`/car/car-list?no=${record.no}`)
  } else if (record.type == 1 && record.order_type == 3) {
    router.push(`/sale/barter?no=${record.no}`)
  }
}

// 收款
const showSettlementModal = ref(false)
const disabledSalesmanSelected = ref(true)
function changeSettlementModal(flag: boolean, record?: any) {
  if (flag) {
    settlementFormData.value.store_id = record.store_id
    settlementFormData.value.order_id = record.id
    settlementFormData.value.account_period_amount = record?.sign?.sign_amount
    settlementFormData.value.salesman_id = record?.salesman_id ? record?.salesman_id : null
    disabledSalesmanSelected.value = record?.salesman_id
  } else {
    settlementFormData.value = {
      ...defaultSettlementFormData
    }
  }
  showSettlementModal.value = flag
}
// 组件ref
const formRef = ref()
const defaultSettlementFormData = {
  store_id: '',
  order_id: '',
  salesman_id: '',
  payment_method: 1,
  account_period_amount: '',
  payment_voucher: '',
  account_period_date: '',
  remark: ''
}
const settlementRules = {
  salesman_id: [{ required: true, message: '请选择业务员', trigger: 'blur' }],
  payment_method: [{ required: true, message: '请选择结算方式', trigger: 'blur' }],
  account_period_date: [{ required: true, message: '请选择欠款日期', trigger: 'blur' }],
  payment_voucher: [{ required: true, message: '请上传凭证', trigger: 'blur' }]
}
const settlementFormData = ref({ ...defaultSettlementFormData })
function submitSettlementForm() {
  formRef.value.validate().then(async () => {
    try {
      const res = await accountingPreiodApi.settled(settlementFormData.value)
      message.success(res.msg)
      changeSettlementModal(false)
    } catch (error) {
      errorSentry.captureError(error.msg)
      message.error(error.msg)
    } finally {
      onSearch()
      return Promise.resolve()
    }
  })
}
</script>
